package ccc.hqu.edu.cn.whatmaps;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

import java.util.ArrayList;
import java.util.List;

public class MenuActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    public MapView mMapView = null;
    public BaiduMap mBaiduMap = null;
    //public LocationClient mLocationClient = null;
    public BDAbstractLocationListener myListener = new MyLocationListener();
    double[] myloc = new double[2];//我的地址
    double[] oploc = new double[2];//目标地址
    private int dis = 10;
    private int state = 1;//1表示出围栏提醒，2表示入围栏提醒
    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;
    private LocationService locService;
    Boolean isfirst = true;
    ImageButton get_location_out;
    ImageButton show_silder;
    Button changeLoc;
    FloatingActionButton startSet;
    TextView text_loc_out;
    GeoCoder mCoder = GeoCoder.newInstance();
    SharedPreferences preferences;
    Window window;

    BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {
        /**
         * 地图单击事件回调函数
         *
         * @param point 点击的地理坐标
         */
        @Override
        public void onMapClick(LatLng point) {
            oploc[0]=point.latitude;
            oploc[1]=point.longitude;

            mCoder.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(point)
                    // POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
                    .radius(100));

            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.marker);
            mBaiduMap.clear();
            OverlayOptions option = new MarkerOptions()
                    .position(point)
                    .perspective(false)
                    .icon(bitmap);
            mBaiduMap.addOverlay(option);
        }

        /**
         * 地图内 Poi 单击事件回调函数
         *
         * @param mapPoi 点击的 poi 信息
         */
        @Override
        public boolean onMapPoiClick(MapPoi mapPoi) {
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        final DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        locService = ((DemoApplication) getApplication()).locationService;
        LocationClientOption mOption = locService.getDefaultLocationClientOption();
        if(preferences.getBoolean("rule",false)){
            mOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        }
        locService.setLocationOption(mOption);
        locService.registerListener(myListener);
        locService.start();

        mMapView =findViewById(R.id.bmapView_out);
        mBaiduMap = mMapView.getMap();
        MapView.setMapCustomEnable(true);
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapClickListener(listener);
        mCoder.setOnGetGeoCodeResultListener(coderlistener);


        text_loc_out = findViewById(R.id.loc_text_out);
        changeLoc = findViewById(R.id.changeLoc_out);
        startSet = findViewById(R.id.btn_start_out);
        get_location_out = findViewById(R.id.get_local_out);
        show_silder = findViewById(R.id.show_silde);


        final String[] ctype = new String[]{"10", "20", "50", "100","500","1000"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_style, ctype);  //创建一个数组适配器
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);     //设置下拉列表框的下拉选项样式

        Spinner spinner = super.findViewById(R.id.outActy_R);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (ctype[position]){
                    case "10":dis = 10;break;
                    case "20":dis = 20;break;
                    case "50":dis = 50;break;
                    case "100":dis = 100;break;
                    case "500":dis = 500;break;
                    case "1000":dis = 1000;break;
                    default:dis = 10;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        show_silder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawer.openDrawer(GravityCompat.START);
            }
        });

        get_location_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapStatusUpdate iMapStatusUpdate;
                LatLng latlng = new LatLng(myloc[0], myloc[1]);
                MapStatus mMapStatus = new MapStatus.Builder()
                        .target(latlng)
                        .build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                iMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.setMapStatus(iMapStatusUpdate);
            }
        });

        startSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MenuActivity.this, RunActivity.class);
                intent.putExtra("oploc",oploc);//此处是传输的坐标
                intent.putExtra("radius",dis);//此处是传输的半径
                intent.putExtra("state",state);//此处是传输状态
                startActivity(intent);
            }
        });

        changeLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MenuActivity.this,SearchActivity.class);
                intent.putExtra("myloc",myloc);
                startActivityForResult(intent,11);
            }
        });

        getPersimmions();
    }

    private Handler locHander = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                BDLocation location = msg.getData().getParcelable("loc");
                MapStatusUpdate mMapStatusUpdate;
                if (location != null) {
                    MyLocationData locData = new MyLocationData.Builder()
                            .accuracy(location.getRadius())
                            .direction(location.getDirection()).latitude(location.getLatitude())
                            .longitude(location.getLongitude()).build();
                    mBaiduMap.setMyLocationData(locData);
                    myloc[0] = location.getLatitude();
                    myloc[1] = location.getLongitude();//设定坐标
                    if (isfirst == true) {
                        LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());
                        MapStatus mMapStatus = new MapStatus.Builder()
                                .target(latlng)
                                .zoom(20)
                                .build();
                        oploc[0] = myloc[0];
                        oploc[1] = myloc[1];
                        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                        mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                        //改变地图状态
                        mBaiduMap.setMapStatus(mMapStatusUpdate);
                        isfirst = false;
                        text_loc_out.setText(location.getAddrStr());
                    }
                }
            } catch (Exception e) {

            }
        }
    };


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            //mLocationClient.stop();
            locService.unregisterListener(myListener);
            locService.stop();
            if (mBaiduMap != null)
                mBaiduMap.clear();
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        if (mBaiduMap != null)
            mBaiduMap.clear();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        //mLocationClient.stop();
        locService.unregisterListener(myListener);
        locService.stop();
        mBaiduMap.setMyLocationEnabled(false);
        super.onDestroy();
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_in) {
            state = 2;
            Toast.makeText(MenuActivity.this,"当前是入围栏提醒状态",Toast.LENGTH_LONG).show();
            startSet.setImageResource(R.drawable.in);
        } else if (id == R.id.nav_out) {
            state = 1;
            Toast.makeText(MenuActivity.this,"当前是出围栏提醒状态",Toast.LENGTH_LONG).show();
            startSet.setImageResource(R.drawable.out);
        } else if (id == R.id.nav_setting) {
            Intent intent = new Intent(MenuActivity.this,SettingActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_about) {
            Intent intent = new Intent(MenuActivity.this,AboutActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_share) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse("https://gitee.com/yarchen/WhatMap.git");
            intent.setData(content_url);
            startActivity(intent);
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 11:
                if (resultCode == RESULT_OK){
                    double locs[] = data.getDoubleArrayExtra("loc");
                    if(locs != null){
                        String name = data.getStringExtra("locName");
                        text_loc_out.setText(name);
                        oploc[0] = locs[0];
                        oploc[1] = locs[1];
                        LatLng locre = new LatLng(locs[0],locs[1]);
                        BitmapDescriptor bitmap = BitmapDescriptorFactory
                                .fromResource(R.drawable.marker);
                        mBaiduMap.clear();
                        OverlayOptions option = new MarkerOptions()
                                .position(locre)
                                .icon(bitmap);
                        mBaiduMap.addOverlay(option);
                        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(locre);
                        mBaiduMap.animateMapStatus(u);
                    }
                }
                break;
        }
    }//接受返回数据

    OnGetGeoCoderResultListener coderlistener = new OnGetGeoCoderResultListener() {
        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
                text_loc_out.setText("未知地点");
                return;
            } else {
                //详细地址
                String address = reverseGeoCodeResult.getAddress();
                if(address == null){
                    text_loc_out.setText("未知地点");
                }else{
                    text_loc_out.setText(address);
                }
            }
        }
    };//用于处理用户点击以显示点击位置

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    class MyLocationListener extends BDAbstractLocationListener {


        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location != null && (location.getLocType() == 161 || location.getLocType() == 66)) {
                Message locMsg = locHander.obtainMessage();
                Bundle locData_b = new Bundle();
                locData_b.putParcelable("loc", location);
                locMsg.setData(locData_b);
                locHander.sendMessage(locMsg);
            }

        }
    }
}
